Namespace("sketch.ui.iphone");

(function(fwk, ui, val) {
    ui.iphone.SegmentedControl = klass(ui.common.StackPanel, {
        __type__: "ui.iphone.SegmentedControl",

        _constructor: function() {
            this.properties.createProperty("numberOfSegments", "Number of segments", 2)
                .editorTemplate("#editor-spinner")
                .addValidator(new val.MinMax(2, 5))
                .bind(EventHandler(this, this._numberOfSegmentsChanged));
            this.properties.createProperty("style", "Style", "plain")
                .possibleValues({plain: "Plain", bordered: "Bordered", bar: "Bar", bezeled: "Bezeled"})
                .editorTemplate("#editor-dropdown")
                .bind(EventHandler(this, this._styleChanged));

            this.children.changed.bind(EventHandler(this, this._childrenChanged));
            this._itemActiveChangedHandler = EventHandler(this, this._itemActiveChanged);

            this.init({
                width: 300,
                orientation: "horiztonal",
                style: "plain"
            });

            this.addItem("First", true);
            this.addItem("Second", false);
            this.dropPositioning("horizontal");
            this.enableGroupLocking(true);
        },

        _childrenChanged: function(){
            this._preventChildrenControl = true;
            this.numberOfSegments(this.children.count());
            this._preventChildrenControl = false;
        },
        _numberOfSegmentsChanged: function(event) {
            if (this._preventChildrenControl){
                return;
            }

            var diff = event.newValue - this.children.count();

            if (diff > 0) {
                while (diff--) {
                    this.addItem("New", false);
                }
            }
            else {
                while (diff++) {
                    var element = this.children.single(function(x){ return x.type() === "right"; });
                    this.remove(element);
                }
            }
        },
        _styleChanged: function(event){
            if (event.newValue === "bar") {
                this.height(ui.iphone.SEGMENTEDCONTROL_HEIGHT_BAR);
            }
            else {
                this.height(ui.iphone.SEGMENTEDCONTROL_HEIGHT);
            }
            this.performArrange();
        },
        _itemActiveChanged: function(event) {
            this._checkActiveItems(event.sender);
        },
        _updateChildrenProperties: function(){
            var activeChild;

            this.children.each(function(i, child) {
                if (activeChild) {
                    child.isPreviousActive(true);
                    activeChild = undefined;
                }
                else{
                    child.isPreviousActive(false);
                }
                if (child.active()){
                    activeChild = child;
                }
            });
        },
        _checkActiveItems: function(item){
            if (item.active()) {
                var activeItems = this.children.where(function(x) { return x.active(); });
                each(activeItems, function(x){
                    if (x !== item) {
                        x.active(false);
                    }
                });
            }
            this._updateChildrenProperties();
        },
        _validateChildrenCountChange: function(diff) {
            return this.properties.numberOfSegments.validateNewValue(this.children.count() + diff).ok;
        },

        addItem: function(label, active) {
            var item = new ui.iphone.SegmentedControlItem();
            item.verticalAlignment("stretch");
            item.label(label);
            item.active(active);
            this.add(item);

            return item;
        },

        bindToChild: function(element){
            element.properties.active.bind(this._itemActiveChangedHandler);
            this.properties.style.bind(element.properties.style.bindingPoint);
            element.style(this.style());
            element.isOrphaned(false);
        },
        unbindFromChild: function(element){
            element.properties.active.unbind(this._itemActiveChangedHandler);
            this.properties.style.unbind(element.properties.style.bindingPoint);
            element.isPreviousActive(false);
            element.isOrphaned(true);
        },

        add: function($super, element){
            this.bindToChild(element);
            this._checkActiveItems(element);
            $super(element);
        },
        insert: function($super, element, index){
            this.bindToChild(element);
            this._checkActiveItems(element);
            $super(element, index);
        },
        remove: function($super, element){
            this.unbindFromChild(element);
            $super(element);
        },
        clear: function($super){
            var that = this;
            this.children.each(function(i, element){
                that.unbindFromChild(element);
            });
            $super();
        },

        canAccept: function(element){
            return element instanceof ui.iphone.SegmentedControlItem;
        },
        canAdd: function(element){
            return this._validateChildrenCountChange(1);
        },
        canRemove: function(element){
            return this._validateChildrenCountChange(-1);
        },
        canInsert: function(element, index){
            return this._validateChildrenCountChange(1);
        },

        resizeDimensions:function() {
            return fwk.ResizeDimension.Horizontal;
        },

        numberOfSegments: function(value){
            return this.properties.numberOfSegments(value);
        },
        style: function(value){
            return this.properties.style(value);
        },

        arrange: function($super) {
            var count = this.children.count();

            if (count === 0) {
                return;
            }

            var childWidth = this.width() / count;

            this.children.each(function(i, child) {
                if (i === 0) {
                    child.type("left");
                } else if (i === count - 1) {
                    child.type("right");
                }
                else {
                    child.type("center");
                }

                child.width(childWidth);
            });

            this._updateChildrenProperties();

            $super();

            this.children.each(function(i, child) {
                child.performArrange();
            });
        }
    });
})(sketch.framework, sketch.ui, sketch.framework.validation);